from .basehandler import require_login, BaseHandler
from . import models, forms

class DefaultHandler(BaseHandler):

	_template_dir = 'user'

	def oninit(self):
		super().oninit()
		user_id = self.get_arg('id')

		if self.user and self.user.id == int(user_id):
			return self.redirect(self.page_url('mine'))
		
		self.target = models.User.objects.filter(id=user_id).first()
		self.target.avatar = self.config.DEFAULT_AVATAR
		self.assign('user', self.target)
		self.assign('menu', self.config.userLeftMenu)

	def index(self):
		return self.forward('article')

	def article(self):
		search = self.get_arg('search', None)
		articles = models.Article.find_public().filter(author=self.target)
		if search:
			articles = articles.filter(title__icontains=search)
		return self.render(articles=articles)

	def info(self):
		data = self.target.iter_label_value(('nickname', 'gender', 'email', 'phone'))
		return self.render(data=data)

	def follow(self):
		users = models.Follow.objects.filter(follower=self.target)
		users = (item.target for item in users)
		return self.render(users=users)

	def fans(self):
		users = models.Follow.objects.filter(target=self.target)
		users = (item.follower for item in users)
		return self.render(users=users)

	def dofollow(self):
		if not self.followed():
			models.Follow.objects.create(follower=self.user, target=self.target)
			self.user.follow_count += 1
			self.target.fans_count += 1
			self.user.save()
			self.target.save()
		return self.goback()

	def unfollow(self):
		models.Follow.objects.filter(follower=self.user, target=self.target).delete()
		self.user.follow_count -= 1
		self.target.fans_count -= 1
		self.user.save()
		self.target.save()
		return self.goback()

	def followed(self):
		return models.Follow.objects.filter(follower=self.user, target=self.target).exists()